<template>
  <div class="addEdit-container">
    <div class="edit-box">
      <!-- head return-->
      <div class="addEdit-head">
        <van-nav-bar title="编辑地址">
          <template #left>
            <van-icon name="arrow-left" size="24" color="black" @click="$router.push('/home/address')" />
          </template>
        </van-nav-bar>
      </div>

      <div class="addEdit">
        <van-address-edit :area-list="areaList" :address-info="addItem" show-postal show-delete show-set-default
          show-search-result :search-result="searchResult" :area-columns-placeholder="['请选择', '请选择', '请选择']"
          @save="onSave" @delete="onDelete" @change-detail="onChangeDetail" />
      </div>
    </div>
  </div>
</template>

<script>
import { Toast } from 'vant'
import { areaList } from '@vant/area-data'
import bus from '@/eventBus.js'

export default {
  data() {
    return {
      searchResult: [],
      areaList,
      // 新增、更改的地址数据
      addItem: {},
      isForOrder: false
    }
  },
  created() {
    // 此状态用于管理从 Address 组件返回时的路由路径
    this.isForOrder = this.$store.state.isForOrder
    // 读取当前需要修改的地址数据
    bus.$on('nowAddress', val => {
      this.addItem = val
    })
  },
  // 通过 eventBus 接收 Address 组件传参，需要在 beforeDestroy() 阶段销毁 $on，否则会造成多次触发事件，导致数据累积
  beforeDestroy() {
    bus.$off('nowAddress')
  },
  methods: {
    // 保存新地址数据
    onSave(newVal) {
      if (this.addItem.id === undefined) {
        Toast('添加成功')
      } else {
        Toast('修改成功')
      }
      var add = newVal.province + newVal.city + newVal.county + newVal.addressDetail
      this.addItem = {
        address: add,
        addressDetail: newVal.addressDetail,
        areaCode: newVal.areaCode,
        city: newVal.city,
        country: newVal.country,
        county: newVal.county,
        id: newVal.id,
        isDefault: newVal.isDefault,
        name: newVal.name,
        postalCode: newVal.postalCode,
        province: newVal.province,
        tel: newVal.tel
      }
      this.$store.commit('addAddress', this.addItem)
      this.$router.push('/home/address')
    },
    // 删除地址数据
    onDelete(newVal) {
      if (newVal.isDefault === true) {
        Toast('不能删除默认地址')
      } else {
        Toast('删除成功')
        this.$store.commit('sumAddress', newVal)
        this.$router.push('/home/address')
      }
    },
    // 详细地址历史记录
    onChangeDetail(val) {
      // if (val) {
      //   this.searchResult = [
      //     {
      //       name: '黄龙万科中心',
      //       address: '杭州市西湖区'
      //     }
      //   ]
      // } else {
      //   this.searchResult = []
      // }
    }
  }
}
</script>

<style lang="less" scoped>
.edit-box {
  position: absolute;
  max-width: 640px;
  width: 100%;
  height: 100%;
  // transform: translateX(-50%);
  background: #ededed;
  z-index: 2;
}
/deep/ .van-address-edit__buttons {
  .van-button--danger {
    background-color: orange;
    border: none;
  }
}
</style>
